#include "SpinBoxWithSlider.h"

SpinBoxWithSlider::SpinBoxWithSlider(const QString& title, int currentValue, int minValue, int maxValue, QWidget *parent) : QWidget(parent)
{
    min = minValue;
    max = maxValue;
    current = currentValue < min ? min : currentValue > max ? max : currentValue;

    box = new QSpinBox(this);
    box -> setMinimum(min);
    box -> setMaximum(max);
    box -> setValue(current);

    slider = new QSlider(Qt::Orientation::Horizontal, this);
    slider -> setMinimum(min);
    slider -> setMaximum(max);
    slider -> setValue(current);

    label = new QLabel(this);
    label -> setText(title);

    layout = new QHBoxLayout(this);
    layout -> addWidget(label);
    layout -> addWidget(slider);
    layout -> addWidget(box);
    setLayout(layout);

	box -> setContentsMargins(0, 0, 0, 0);
	slider -> setContentsMargins(0, 0, 0, 0);
	label -> setContentsMargins(0, 0, 0, 0);
	setContentsMargins(0, 0, 0, 0);
	layout -> setAlignment(Qt::AlignmentFlag::AlignCenter);

    connect(box, SIGNAL(valueChanged(int)), this, SLOT(ValueChangedHandle(int)));
    connect(slider, SIGNAL(valueChanged(int)), this, SLOT(ValueChangedHandle(int)));

}

SpinBoxWithSlider::~SpinBoxWithSlider()
{
    delete layout;
    delete slider;
    delete box;
    delete label;
}

void SpinBoxWithSlider::SetMinValue(int v)
{
    min = v;
    current = current < min ? min : current > max ? max : current;
    box -> setMinimum(min);
    slider -> setMinimum(min);
    box -> setValue(current);
    slider -> setValue(current);
}

void SpinBoxWithSlider::SetMaxValue(int v)
{
    max = v;
    current = current < min ? min : current > max ? max : current;
    box -> setMaximum(max);
    slider -> setMaximum(max);
    box -> setValue(current);
    slider -> setValue(current);
}

void SpinBoxWithSlider::SetValue(int v)
{
    current = v;
    current = current < min ? min : current > max ? max : current;
    box -> setValue(current);
    slider -> setValue(current);
    emit(ValueChanged(v));
}

void SpinBoxWithSlider::ValueChangedHandle(int v)
{
    if(v == current)
        return;
    SetValue(v);
}

void SpinBoxWithSlider::SetTitle(const QString &title)
{
    label -> setText(title);
}

int SpinBoxWithSlider::GetValue()
{
    return current;
}

